<?php

class PsptoolController extends AppController {
	public $name = 'psptool';
	
	function beforeFilter() {
 	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('shortcutdown','upfile','pupfile','baidumap','getbaidumap','ad','upimages'); 

	}
    //下载本站快捷键
	public function shortcutdown() {
        $Shortcut = "[InternetShortcut] 
        URL=".Request::$base." 
        IDList= 
        IconIndex=43
        IconFile=C:\Windows\system32\SHELL32.dll
        HotKey=1626
        [{000214A0-0000-0000-C000-000000000046}] 
        Prop3=19,2 
        "; 
        Header("Content-type: application/octet-stream"); 
        header("Content-Disposition: attachment; filename=".Request::$base.".url;"); 
        echo $Shortcut; 
        exit;		
	}
	
	public function upimages() {	
	
		//截图质量（限jpg、70-100，100为最好质量）
		$web['pic_quality']=75;
		//截图尺寸（大、小二种，分宽、高）
		$web['img_w_b'] = 96;
		$web['img_h_b'] = 96;
		$web['img_w_s'] = 48;
		$web['img_h_s'] = 48;
		//截图类型（限jpg、gif、png）建议gif，这样可以上传小动画
		$web['img_up_format']='gif';	
	
		$ptype = Request::get_args('ptype');	 
        if ($ptype == 1) {
            $picviewout	= '';	
            Loader::import('lib.cupload');		
            $up = new upload('jpg|gif|png',1024,'attach');
            $up->set_dir(APP_ROOT . Param::read('upfiles.path') . '/psptest/',"{y}/{m}/{d}");
            $fs = $up->execute();
			$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
            $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';				
	        $realtxt=$fs[0];
			
	        if($realtxt['flag']==1){
		        $fileSrcStr = ltrim(str_replace(APP_ROOT . Param::read('upfiles.path'),"",$realtxt['dir']),'/').$realtxt['name'];
				//$post[0]['uid']=$this->my->id;
				$post[0]['img_size']=$realtxt['size'];
				$post[0]['upl_time'] = date("Y-m-d H:i:s",time());
				$post[0]['img_url'] = $fileSrcStr;
				$post[0]['is_intro_img']='1';
				$picviewout .='<script>document.cookie="162100screenshotsImg="+encodeURIComponent(\''.Request::UpfileDir($fileSrcStr).'\')+"; path=/;";</script>';

				$picviewout .=	'<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td><span class="alert"></span>图片上传成功！</td>
					  </tr>
					</table>
					<script>location.href=\''.Router::url('psptool/upimages/?ptype=5').'\';</script></td>
					  </tr>
					</table>';				
                $this->set('picviewout', $picviewout);
			    $this->render("upimages_1");				
            }else {
				$picviewout .=	'<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td><span class="alert"></span>图片上传不成功！</td>
					  </tr>
					</table>
					<script>location.href=\''.Router::url('psptool/upimages/').'\';</script></td>
					  </tr>
					</table>';				
                $this->set('picviewout', $picviewout);
			    $this->render("upimages_1");			
            }			
	    }else if ($ptype == 2){		
			$filename = $_POST['purl2'];
            $picviewout	= '';			
			if ($filename == '' || !preg_match('/^https?:\/\/.+\.(jpg|gif|png)$/i', $filename, $matches)) {
				$picviewout	= '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td>
				<span class="err"></span>图片URL输入不合法！网址以http://开头！图片格式限(jpg|gif|png)。</td>
				  </tr>
				</table><p><a href="'.Router::url('psptool/upimages/').'">重载图片</a></p></td>
				  </tr>
				</table>';					
				$this->set('picviewout', $picviewout);			
				$this->render("upimages_1");
			}
			if (!$im = @file_get_contents($filename)) {
				$picviewout	= '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td>
				<span class="err"></span>无法获取此图片！请确定图片URL正确。</td>
				  </tr>
				</table><p><a href="'.Router::url('psptool/upimages/').'">重载图片</a></p></td>
				  </tr>
				</table>';					
				$this->set('picviewout', $picviewout);			
				$this->render("upimages_1");			
		    }
		    if (strlen($im) > 2 * 1024 * 1024) {
				$picviewout	= '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td>
				<span class="err"></span>图片上传不成功！链接的文件请小于2MB。</td>
				  </tr>
				</table><p><a href="'.Router::url('psptool/upimages/').'">重载图片</a></p></td>
				  </tr>
				</table>';					
				$this->set('picviewout', $picviewout);			
				$this->render("upimages_1");		   
		    }
		    $t = strtolower($matches[1]);		   

		    $time = time();
		    $filename_1 = APP_ROOT . Param::read('upfiles.path') . '/psptest/'.date('Y',$time).'/'.date('m',$time).'/'.date('d',$time).'/'.date('Ymdhis',$time).mt_rand(10,99).'.'.$t;
		    write_file($filename_1, $im);		   
			$cimg_o_10 = $this->base . '/' . trim(trim(str_replace(APP_ROOT,"",$filename_1),'/'),'\\') ;		   
		   
			$picviewout .='<script>document.cookie="162100screenshotsImg="+encodeURIComponent(\''.$cimg_o_10.'\')+"; path=/;";</script>';		   
	   
			$picviewout .='<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td><span class="alert"></span>头像上传成功！</td>
			  </tr>
			</table>
			<script>location.href=\''.Router::url('psptool/upimages/?ptype=5').'\';</script></td>
			  </tr>
			</table>';					
			$this->set('picviewout', $picviewout);			
			$this->render("upimages_1");		

	    }else if ($ptype == 4){		
			if (extension_loaded('gd')) {
				if (!function_exists('gd_info')) {
				    exit('重要提示：你的gd版本很低，图片处理功能可能受到约束。');
				}
			} else {
				exit('重要提示：你尚未加载gd库，图片处理功能可能受到约束。');
			}
            $picviewout	= '';				
			$cimg_o = $_COOKIE['162100screenshotsImg'];
			$cimg_o = APP_ROOT . DS .trim(str_replace($this->base,"",$cimg_o),'/') ;

			$img_info = getimagesize($cimg_o);
			$_POST['imgw'] = $_POST['imgw'] == $img_info[0] ? $_POST['imgw'] : $img_info[0];
			$_POST['imgh'] = $_POST['imgh'] == $img_info[1] ? $_POST['imgh'] : $img_info[1];
			//如果图片尺寸符合标准而直接提交的话
			if ($_POST['imgto'] == 1) {
				if ($_POST['imgw'] > $web['img_w_b'] || $_POST['imgh'] > $web['img_h_b']) {
					$picviewout	= '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td>
					<span class="err"></span>图片尺寸不符标准！</td>
					  </tr>
					</table><p><a href="'.Router::url('psptool/upimages/').'">重载图片</a></p></td>
					  </tr>
					</table>';					
					$this->set('picviewout', $picviewout);
					$this->render("upimages_1");	
				}
			} else {
				$cut_x = $_POST['imgw'] / $_POST['noww'] * $_POST['px'];
				$cut_y = $_POST['imgh'] / $_POST['nowh'] * $_POST['py'];
				$cut_w = $_POST['imgw'] / $_POST['noww'] * $_POST['pw'];
				$cut_h = $_POST['imgh'] / $_POST['nowh'] * $_POST['ph'];
				if ($_POST['pw'] / $_POST['ph'] > $web['img_w_b'] / $web['img_h_b']) {
					$ow1 = $web['img_w_b'];
					$oh1 = ceil($ow1 * $_POST['ph'] / $_POST['pw']);
				} else {
					$oh1 = $web['img_h_b'];
					$ow1 = ceil($oh1 * $_POST['pw'] / $_POST['ph']);
				}

				if (run_img_resize($cimg_o, $cimg_o, $cut_x, $cut_y, $cut_w, $cut_h, $cut_w, $cut_h, $web['pic_quality']) && run_img_resize($cimg_o, $cimg_o, 0, 0, $ow1, $oh1, false, false, $web['pic_quality'])) {
				  $ow = $_POST['pw'];
				  $oh = $_POST['ph'];
				  if ($ow1 / $oh1 >= 240 / 180) {
					if ($ow1 > 240) {
					  $ow1 = 240;
					  $oh1 = ceil(240 * $_POST['ph'] / $_POST['pw']);
					}
				  } else {
					if ($oh1 > 180) {
					  $oh1 = 180;
					  $ow1 = ceil(180 * $_POST['pw'] / $_POST['ph']);
					}
				  }
				} else {
					$picviewout	.= '<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
					  <tr>
						<td>
					<span class="err"></span>截图失败！</td>
					  </tr>
					</table><p><a href="'.Router::url('psptool/upimages/').'">重载图片</a></p></td>
					  </tr>
					</table>';					
					$this->set('picviewout', $picviewout);
					$this->render("upimages_1");				
				}
			}
			
			$cimg_o = typeto($cimg_o, $web['img_up_format']);	
			$cimg_o_11 = trim(trim(str_replace(APP_ROOT,"",$cimg_o),'/'),'\\');			
			$cimg_o_11 = ltrim(str_replace(trim(Param::read('upfiles.path'),'/') ,"",$cimg_o_11),'/');

			
			$cimg_o_10 = $this->base . '/' . trim(trim(str_replace(APP_ROOT,"",$cimg_o),'/'),'\\') ;
			$picviewout .='<script>document.cookie="162100screenshotsImg="+encodeURIComponent(\''.$cimg_o_10.'\')+"; path=/;";</script>';
			$t = time();

			$picviewout .=	'<iframe id="imgifr" name="imgifr" src="'.$cimg_o_10.'" style="display:none"></iframe>
			<script>
			window.onload = function() {
			  document.getElementById(\'imgifr\').contentWindow.location.reload(true);
			  if(parent!=self){
				if(parent.document.getElementById(\'screenshotsShow\')!=null) {
				  parent.document.getElementById(\'screenshotsShow\').innerHTML=\'<img src="'.$cimg_o_10.'?'.$t.'" />\';
				}
				if(parent.document.getElementById(\'UP_user_logo\')!=null) {
				  parent.document.getElementById(\'UP_user_logo\').value=\''.$cimg_o_11.'\';
				}				
			  }
			}
			</script>';	
		    $picviewout .=	'<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td>
			<span class="err"></span>'.'截图成功！<div class="sword">（可点右键另存为）</div><center><a href="'.$cimg_o_10.'" target="_blank"><img class="i_face_small" src="'.$cimg_o_10.'?'.$t.'" /></a></center>'.'</td>
			  </tr>
			</table><p><a href="'.Router::url('psptool/upimages/').'">重载图片</a></p></td>
			  </tr>
			</table>';				
/*			
			$picviewout .=	'<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td align="center"><table style="margin:auto" border="0" cellspacing="0" cellpadding="0">
				  <tr>
					<td><span class="alert"></span>'.'截图成功！<div class="sword">（可点右键另存为）</div><center><a href="'.$cimg_o_10.'" target="_blank"><img class="i_face_small" src="'.$cimg_o_10.'?'.$t.'" /></a></center>'.'</td>
				  </tr>
				</table>
				<script>location.href=\''.Router::url('psptool/upimages/?ptype=5').'\';</script></td>
				  </tr>
				</table>';	
*/

			$this->set('picviewout', $picviewout);
			$this->render("upimages_1");			
		
	    }else if ($ptype == 5){				
			$cimg_o = $_COOKIE['162100screenshotsImg'];
			$cimg_o = trim(trim(str_replace($this->base,"",$cimg_o),'/'),'\\');			
			$cimg_o = ltrim(str_replace(trim(Param::read('upfiles.path'),'/') ,"",$cimg_o),'/');

            $picviewout	= '';			
			$t = time();
			$picviewout .=	'<iframe id="imgifr" name="imgifr" src="'.Request::UpfileDir($cimg_o).'" style="display:none"></iframe>
			<script>
			window.onload = function() {
			  document.getElementById(\'imgifr\').contentWindow.location.reload(true);
			  if(parent!=self){
				if(parent.document.getElementById(\'UP_user_logo\')!=null) {
				  parent.document.getElementById(\'UP_user_logo\').value=\''.$cimg_o.'\';
				}				
			  }
			}
			</script>';	
			$this->set('picviewout', $picviewout);			
			$this->render("upimages_2");		
		}
	}
	
	public function upfile() {		 
		$tf = Request::get_args('tf');
		$act = Request::get_args('act'); 	
		$jsfun = Request::get_args('jsfun'); 			
		$uppic = Request::get_args('uppic'); 		
		$picurl = Request::get_args('picurl');
		$updir = str_replace(array('\\','/','.','*'), '',Request::get_args('updir'));		
		if($act == 'post')
		{		
			$query = array(
				'conditions' => array('user.id' => $this->my->id), 
				'fields' => array('user.*'), 
			);
			$user_info = POP::exe('[@@:UM user][@@:QU find:first]',$query);				
			$row = $user_info['user'];		
		    $filedname = trim(str_replace(array("UP_"),array(""),$uppic));        
            Loader::import('lib.cupload');		
            $up = new upload('jpg|gif|png',1024,'attach');
            $up->set_dir(APP_ROOT . Param::read('upfiles.path') . '/'.$updir.'/',"{y}/{m}/{d}");
            $fs = $up->execute();
			$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
            $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';				
	        $realtxt=$fs[0];			
	        if($realtxt['flag']==1){
		        $fileSrcStr = ltrim(str_replace(APP_ROOT . Param::read('upfiles.path'),"",$realtxt['dir']),'/').$realtxt['name'];
				$post[0]['uid']=$this->my->id;
				$post[0]['img_size']=$realtxt['size'];
				$post[0]['upl_time'] = date("Y-m-d H:i:s",time());
				$post[0]['img_url'] = $fileSrcStr;
				$post[0]['is_intro_img']='1';
				if(is_array($post)){
					$set = $value = $dot = '';
					foreach($post as $key=>$val){
						$row['count_imgsize']+=$val['img_size'];
						$value .= $dot."(";
						$dot = '';
						foreach($val as $k=>$v) {
							if($key==0){
								$set .= $dot."`$k`";
							}
							$value .= $dot."'$v'";
							$dot = ",";
						}
						$value .= ")";
					}
					$sql_part = "($set) values $value";
				} else {
					exit('insert_items not array');
				}

				$query = "[_insert] [_table imgsize:no] $sql_part";				
				$suc = $id= POP::exe('[@@:UM imgsize][@@:QU insert]',$query);	
				if($suc){
					$update_items['user']['count_imgsize']=$row['count_imgsize'];	
					$query = array();
					$query['keyid'] = $row['id'];
					$query['set']= $update_items;					
					POP::exe('[@@:UM user][@@:QU save]',$query);						
				}				
		 	}	 
		    $newfile = $fileSrcStr;	       
			if($picurl) {
			  
		    }		
		    $pic_url = $newfile;
            if($tf=='pic'){
	            echo "<img src='{$pic_url}' id='upsrc' width='100px' height='100px'><br/><A HREF='".Router::url('psptool/upfile/')."?tf=$tf&picurl=$newfile&updir=$updir&jsfun=$jsfun&uppic=$uppic'>修改图片</A>";			  
			}else {
	            echo "<A HREF='".Router::url('psptool/upfile/')."?tf=$tf&picurl=$newfile&updir=$updir&jsfun=$jsfun&uppic=$uppic'>修改文件</A>";			  
			}
			echo "<script>
					if(self==top){
						window.opener.$jsfun('$newfile','$uppic');
						window.self.close();
					}else{
						window.parent.$jsfun('$newfile','$uppic');
					}
				 </script>";					
			exit;		
		}	
        $this->set('jsfun', $jsfun);		
        $this->set('uppic', $uppic);				
        $this->set('picurl', $picurl);
        $this->set('tf', $tf);	
        $this->set('updir', $updir);		
	}	
	
	public function pupfile() {
		$tf = Request::get_args('tf');
		$act = Request::get_args('act'); 	
		$jsfun = Request::get_args('jsfun'); 			
		$uppic = Request::get_args('uppic'); 		
		$pic_url = Request::get_args('picurl');
		$updir = str_replace(array('\\','/','.','*'), '',Request::get_args('updir'));		
		if($act == 'post')
		{				       
            Loader::import('lib.cupload');		
            $up = new upload('jpg|gif|png',1024,'attach');
            $up->set_dir(APP_ROOT . Param::read('upfiles.path') . '/'.$updir.'/',"{y}/{m}/{d}");
            $fs = $up->execute();
			$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
            $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';				
	        $realtxt=$fs[0];			
	        if($realtxt['flag']==1){			
		        $fileSrcStr = ltrim(str_replace(APP_ROOT . Param::read('upfiles.path'),"",$realtxt['dir']),'/').$realtxt['name'];
				$post[0]['uid']=$this->my->id;
				$post[0]['img_size']=$realtxt['size'];
				$post[0]['upl_time'] = date("Y-m-d H:i:s",time());
				$post[0]['img_url'] = $fileSrcStr;
				$post[0]['is_intro_img']='1';
				$user_info = $this->user->find('first', array('conditions' => array('user.id' => $this->my->id)));	
				$row = $user_info['user'];				
				if(is_array($post)){
					$set = $value = $dot = '';
					foreach($post as $key=>$val){
						$row['count_imgsize']+=$val['img_size'];
						$value .= $dot."(";
						$dot = '';
						foreach($val as $k=>$v) {
							if($key==0){
								$set .= $dot."`$k`";
							}
							$value .= $dot."'$v'";
							$dot = ",";
						}
						$value .= ")";
					}
					$sql_part = "($set) values $value";
				} else {
					exit('insert_items not array');
				}
				$sql = "insert `".$this->user->tablePrefix."img_size` $sql_part";
				$suc = $this->user->query($sql);
				$id=mysql_insert_id();	
				if($suc){
					$update_items['user']['count_imgsize']=$row['count_imgsize'];
					$this->user->id = $row['id'];
					$this->user->importOldData = false;								
					$safeData = $update_items;
					$this->user->set( $safeData );
					$this->user->save($safeData);	
				}				
		 	}
            if(empty($pic_url))	$pic_url='';		
		    $pic_url .= $id .',';
		    $nowpic = $id .',';			
            if($tf=='pic'){
	            echo "<img src='{$pic_url}' id='upsrc' width='100px' height='100px'><br/><A HREF='".Router::url('psptool/pupfile/')."?tf=$tf&picurl=$newfile&updir=$updir&jsfun=$jsfun&uppic=$uppic'>修改图片</A>";			  
			}else {
	            echo "<A HREF='".Router::url('psptool/pupfile/')."?tf=$tf&picurl=$pic_url&updir=$updir&jsfun=$jsfun&uppic=$uppic'>添加文件</A>";			  
			}
			echo "<script>
					if(self==top){
						window.opener.$jsfun('$nowpic','$uppic');
						window.self.close();
					}else{
						window.parent.$jsfun('$nowpic','$uppic');
					}
				 </script>";					
			exit;		
		}	
        $this->set('jsfun', $jsfun);		
        $this->set('uppic', $uppic);				
        $this->set('picurl', $pic_url);
        $this->set('tf', $tf);	
        $this->set('updir', $updir);		
	}	
	
    //百度地图
    public function baidumap(){
		$point = Request::get_args("point");
		$callback = Request::get_args("callback");		
		$this->set('point', $point);
		$this->set('callback', $callback);		
		$this->render("baidumap");
    }	
    //百度地图
    public function getbaidumap(){
		$point = Request::get_args("point");
		$content = Request::get_args("content");
		$title = Request::get_args("title");
		$width = Request::get_args("width");
		$height = Request::get_args("height");
		$this->set('width', $width);		
		$this->set('height', $height);		
		$this->set('point', $point);
		$this->set('content', $content);
		$this->set('title', $title);		
		$this->render("getbaidumap");
    }	

    public function ad(){
		$act = Request::get_args("act");
        if($act =='js') {
			unset($_AD_label,$AD_label);
			require_once(TMP."/cache/ad/ad_cache.php");
			$show=$_AD_label[$_GET['adid']];
			//对javascript进行特别处理
			if(eregi("<SCRIPT",$show)){
				preg_match_all("/<SCRIPT([^>]*)>(.*?)<\/SCRIPT>/is",$show,$array);
				foreach($array[1] AS $key=>$value){
					//一般联盟广告会出现这种情况
					if(eregi("src=",$value)){
						$value=str_replace("'","\'",$value);
						echo "document.write('<SCRIPT$value><\/SCRIPT>');";
					}else{
						echo $array[2][$key];
					}
				}
				$show=preg_replace("/(.*?)<SCRIPT([^>]*)>(.*?)<\/SCRIPT>(.*?)/is","\\1\\4",$show);
			}
			$show=str_replace("\n","",$show);
			$show=str_replace("\r","",$show);
			$show=str_replace("'","\'",$show);
			echo "document.write('$show');";
			exit;		
		}else if($act =='jump') {
			$this->loadModel('adplace');
			$_pre = $this->adplace->tablePrefix;
			$id = $_GET['id'];
			$u_id = $_GET['u_id'];
		    $rs = $this->adplace->query("SELECT * FROM {$_pre}ad_place a WHERE id='$id'");	
            if(!empty($rs)) {			
				$rs = $rs['a'];
				$acodedb=unserialize($rs['adcode']);
				if($acodedb){
					$this->adplace->query("UPDATE {$_pre}ad_place SET hits=hits+1 WHERE id='$id'");
					if($u_id){
						$this->adplace->query("UPDATE {$_pre}ad_user SET u_hits=u_hits+1 WHERE u_id='$u_id'");
					}
					if($acodedb['linkurl']&&!$u_id){
						header("location:".$acodedb['linkurl']);
					}else{
						$url=base64_decode($url);
						header("location:$url");
					}		
					exit;
				}
            }				
		}
    }	
	
}
//处理缩略图
function run_img_resize($img, $resize_img_name, $dx, $dy, $resize_width, $resize_height, $w, $h, $quality) {
  $img_info = @getimagesize($img);
  $width = $img_info[0];
  $height = $img_info[1];
  $w = $w == false ? $width : $w;
  $h = $h == false ? $height : $h;
  switch ($img_info[2]) {
    case 1 :
    $img = @imagecreatefromgif($img);
    break;
    case 2 :
    $img = @imagecreatefromjpeg($img);
    break;
    case 3 :
    $img = @imagecreatefrompng($img);
    break;
  }
  if (!$img) return false;
  if (function_exists('imagecopyresampled')) {
    $resize_img = @imagecreatetruecolor($resize_width, $resize_height);
    $white = @imagecolorallocate($resize_img, 255, 255, 255);
    @imagefilledrectangle($resize_img, 0, 0, $resize_width, $resize_height, $white);// 填充背景色
    @imagecopyresampled($resize_img, $img, 0, 0, $dx, $dy, $resize_width, $resize_height, $w, $h);
  } else {
    $resize_img = @imagecreate($resize_width, $resize_height);
    $white = @imagecolorallocate($resize_img, 255, 255, 255);
    @imagefilledrectangle($resize_img, 0, 0, $resize_width, $resize_height, $white);// 填充背景色
    @imagecopyresized($resize_img, $img, 0, 0, $dx, $dy, $resize_width, $resize_height, $w, $h);
  }
  //if(file_exists($resize_img_name)) unlink($resize_img_name);
  switch ($img_info[2]) {
    case 1 :
    @imagegif($resize_img, $resize_img_name);
    break;
    case 2 :
    @imagejpeg($resize_img, $resize_img_name, $quality); //100质量最好，默认75
    break;
    case 3 :
    @imagepng($resize_img, $resize_img_name);
    break;
  }
  @imagedestroy($resize_img);
  return true;
}
//转换格式
function typeto($im, $format) {
  $fr = strtolower(ltrim(strrchr($im, '.'), '.'));
  if ($format == 'jpg') $f = 'jpeg';
  elseif ($format == 'png') $f = 'png';
  else $f = 'gif';
  if ($fr != $format) {
    switch ($fr) {
      case 'gif':
      $img = imagecreatefromgif($im);
      break;
      case 'png':
      $img = imagecreatefrompng($im);
      break;
      case 'jpg':
      $img = imagecreatefromjpeg($im);
      break;
    }
    @unlink($im);
    $im = preg_replace("/\.".preg_quote($fr)."$/", "", $im).".".$format;
    eval('
    if(image'.$f.'($img, $im)) {
      imagedestroy($img);
    }
    ');
  }
  return $im;
}

?>